package com.katus.tileserver.controller;

import com.katus.tileserver.bean.Result;
import com.katus.tileserver.dao.UserDao;
import com.katus.tileserver.entity.User;
import com.katus.tileserver.entity.UserUpdate;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.UUID;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserDao userDao;

    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    @ResponseBody
    public Result regist(@RequestBody User user, HttpSession session) {
        try {
            user.setUuid(UUID.randomUUID().toString());
            user.setRole((short) 1);
            user.setLevel((short) 0);
            user.setReg_time(Timestamp.from(Instant.now()));
            userDao.createUser(user);
            session.setAttribute("userId", user.getUuid());
            return Result.success().setMessage("注册成功，登陆！");
        } catch (Exception e) {
            return Result.error().setMessage("注册失败：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestBody User user, HttpSession session) {
        try {
            User tmp = userDao.getUser(user.getUserId(), user.getPwd());
            session.setAttribute("userId", tmp.getUuid());
            return Result.success().setMessage("登陆成功！");
        } catch (Exception e) {
            return Result.error().setMessage("登陆失败：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/update/pwd", method = RequestMethod.POST)
    @ResponseBody
    public Result updatePwd(@RequestBody UserUpdate user) {
        try {
            User tmp = userDao.getUser(user.getUserId(), user.getSourcePwd());
            tmp.setPwd(user.targetPwd);
            userDao.updatePwd(tmp);
            return Result.success().setMessage("密码修改成功！");
        } catch (Exception e) {
            return Result.error().setMessage("密码修改失败：" + e.getMessage());
        }
    }

}
